var q = {
    pagenum: 1,
    pagesize: 2,
    cate_id: '',
    state: ''
}

template.defaults.imports.dateformat = function (time) {
    var dt = new Date()
    var y = dt.getFullYear();
    var m = (dt.getMonth() + 1).toString().padStart(2, "0")
    var d = (dt.getDate()).toString().padStart(2, "0")

    var hh = (dt.getHours()).toString().padStart(2, "0")
    var mm = (dt.getMinutes()).toString().padStart(2, "0")
    var ss = (dt.getSeconds()).toString().padStart(2, "0")
    var str = `${y}年${m}月${d}日${hh}时${mm}分${ss}秒`
    return str;
}
$(function () {

    inittable();
    initcate();
});
// 获取文章列表数据
function inittable() {
    $.ajax({
        type: 'get',
        url: '/my/article/list',
        data: q,
        success: function (res) {
            if (res.status != 0) return layer.msg('获取数据失败')
            console.log('成功')
            var str = template('tpl', res);
            $('tbody').html(str)
            //分页
            renderPage(res.total)//total数据总条数
        }
    })
}

// 下拉菜单
function initcate() {
    $.ajax({
        type: 'get',
        url: '/my/article/cates',
        success: function (res) {
            console.log(res)
            var str = template("cate-tpl", res)
            $('[ name="cate_id"]').html(str);
            layui.form.render('select');
        }
    })
}


$('#filites').on('submit', function (e) {
    e.preventDefault();
    q.cate_id = $('[name = "cate_id"]').val();
    q.state = $('[name = "state"]').val();
    inittable();

});
// 删除功能
$('tbody').on('click', '.remove', function () {
    var id = $(this).attr('data-id');
    layer.confirm('确定要删除?', { icon: 3, title: '提示' }, function (index) {
        //do something
        // 销毁凭证
        $.ajax({
            type: 'get',
            url: '/my/article/deletecate/' + id,
            success: function (res) {
                if (res.status !== 0) return layer.msg('删除失败')
                layer.msg('删除成功');
                if ($('.remove').length == 1) {
                    q.pagenum = q.pagenum == 1 ? 1 : q.pagenum - 1;
                }
                inittable();

            }
        })
        layer.close(index)
    });
})

//分页制作
function renderPage(total) {
    // console.log(total)
    layui.laypage.render({
        elem: 'pageBox',//注意这里的testl是id
        count: total,//数据总数
        limit: q.pagesize,//每页的条数
        curr: q.pagenum,//当前页面
        limits: [2, 3, 4, 5],
        layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
        jump: function (obj, first) {
            console.log(obj)
            q.pagenum = obj.curr;
            q.pagesize = obj.limit;
            if (!first) {
                inittable();
            }
        }
    })
}